from multiprocessing import freeze_support
from LocalTickLoader import LocalTickLoader
from core.RawMDProcessor import RawMDProcessor
from core.StrategyManager import StrategyManager
from MockTrader import MockTrader
from TestStrategy import TestStrategy
from BenchmarkStrategy import BenchmarkStrategy
from core.PublicContext import PublicContext
from core.Logger import Logger
import time
import json


def main():
    strategies_initer = [TestStrategy, BenchmarkStrategy]

    # 创建PublicContext
    public_context = PublicContext('syn')

    # 创建logger
    logger = Logger('./log.txt')
    public_context.logger = logger
    logger.public_context = public_context
    logger.start()
    logger.log_message('Logger started.')

    # 创建策略管理器
    strategy_manager = StrategyManager()
    strategy_manager.public_context = public_context

    # 创建Trader
    trader = MockTrader()
    trader.initialize({'TestStrategy': {'300416': {'sellable_position': 200,
                                                   'unsellable_position': 0,
                                                   'locked_position': 0},
                                        'cash': 100000},
                       'Benchmark': {'cash': 10000}})
    trader.public_context = public_context
    trader.strategy_manager = strategy_manager
    public_context.trader = trader
    trader.start()

    # raw_md_listener: 中转原始行情
    raw_md_listener = RawMDProcessor()
    raw_md_listener.public_context = public_context
    raw_md_listener.stg_manager = strategy_manager

    # 新建策略实例
    # strategy_manager.register_strategy(TestStrategy())
    # strategy_manager.register_strategy(BenchmarkStrategy())
    for initer in strategies_initer:
        strategy_manager.register_strategy(initer())
    strategy_manager.initialize()
    time.sleep(2)

    # ----------------------------
    # 准备工作完成，开始从文件中加载行情
    local_md_loader = LocalTickLoader()
    local_md_loader.set_data_path('./tickdata/md_2020-09-04.txt')
    local_md_loader.set_md_queue(raw_md_listener.raw_md_queue)

    # 开启行情线程
    raw_md_listener.start()
    local_md_loader.start()

    # 等待今日行情结束
    while True:
        if public_context.get_current_time() < "15:31:00":
            time.sleep(1)
            continue
        break

    # 开始收盘工作
    print('--> Start clearing <--')
    # 通知各个组件退出
    raw_md_listener.finish()
    trader.finish()
    # 打印结算结果
    trader.print_orders()
    print(trader.portfolio)
    trader.clearing()
    print(trader.portfolio)
    print(trader.get_market_value())


    logger.finish()
    time.sleep(1)
    print('System shutting down.')
    return 0


if __name__ == '__main__':
    freeze_support()
    main()

